import Vue from 'vue'
import VueRouter from 'vue-router'
import routes from './routes'
import store from '@/store'
Vue.use(VueRouter)
const router = new VueRouter({
  routes,
  scrollBehavior (to, from, savedPosition) {
    return { x: 0, y: 0 }
  }
})
router.beforeEach(async (to, from, next) => {
  let token = store.state.user.token
  let userInfo = store.state.user.userInfo
  if (token) {
    if (to.path === '/login') {
      next('/')
    } else {
      if (userInfo.name) {
        next()
      } else {
        try {
          await store.dispatch('getUserInfo')
          next()
        } catch (error) {
          store.dispatch('clearToken')
          next('/login')
        }
      }
    }
  } else {
    next()
  }
})
const VueRouterPush = VueRouter.prototype.push
const VueRouterReplace = VueRouter.prototype.replace
VueRouter.prototype.push = function (loaction, resolved, rejected) {
  if (!rejected && !resolved) VueRouterPush.call(this, loaction).catch(() => { })
  else VueRouterPush.call(this, loaction, resolved, rejected)
}
export default router